<template>
	<view>
		<view class="bg">
			<image v-if="isDayOrNightSimple()=='day'" class="bg-img" src="/static/my-bg-day.png"></image>
			<image v-else class="bg-img" src="/static/my-bg-night.png"></image>

			<view class="status-bar"></view>
			<view class="nav-title">我的</view>
			<view class="user-bg">
				<image class="head" mode="aspectFill" :src="avatarUrl"></image>
				<!-- #ifdef MP-WEIXIN -->
				<button v-if="nickName==''" class="login-btn" open-type="getUserInfo"
					@getuserinfo="getuserinfo">点击登录</button>
				<view v-else class="nickName">{{nickName}}</view>
				<!-- #endif -->

				<!-- #ifndef MP-WEIXIN -->
				<button v-if="nickName==''" class="login-btn" @click="toLogin">点击登录</button>
				<view v-else class="nickName">{{nickName}}</view>
				<!-- #endif -->
				
				<view v-if="nickName!==''" class="edit" @click="handleEdit">
					<view>编辑</view>
					<uni-icons style="margin-top: 2px;" type="forward" size="15" color="#fff"></uni-icons>
				</view>
			</view>
		</view>
		
		<view v-if="nickName!==''" class="content" @click="handleRank">
			<view class="title">
				<uni-icons type="vip" size="30" color="#FFD700"></uni-icons>
				<view class="title-text">排行榜</view>
			</view>
			<uni-icons type="forward" size="20" color="#6c7698"></uni-icons>
		</view>
		
		<view v-if="nickName!==''" class="content">
			<view class="title">
				<uni-icons type="help" size="30" color="#FFD700"></uni-icons>
				<view class="title-text">意见反馈</view>
			</view>
			<uni-icons type="forward" size="20" color="#6c7698"></uni-icons>
			
			<button class="feedback" open-type="feedback"></button>
		</view>
		
		<view v-if="nickName!==''" class="content" @click="handleQuit">
			<view class="title">
				<uni-icons type="redo" size="30" color="#999"></uni-icons>
				<view class="title-text">退出登录</view>
			</view>
			<uni-icons type="forward" size="20" color="#999"></uni-icons>
		</view>
		
		<view v-else class="noData">
			<image style="width: 300rpx;height: 300rpx;" src="/static/empty.png"></image>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'

	const avatarUrl = ref("/static/Rubik-s.png")
	const nickName = ref("")
	const userInfo = ref()

	onShow(() => {
		try {
			const value = uni.getStorageSync("userInfo");
			if (value) {
				userInfo.value = value
				avatarUrl.value = value.avatarUrl
				nickName.value = value.nickName
			}
		} catch (e) {
			console.log(e)
		}
	})
	
	// 编辑个人信息
	function handleEdit(){
		uni.navigateTo({
			url:"/pages/my/profile/profile"
		})
	}
	
	// 登录或注册
	async function getuserinfo(e) {
		// console.log('getuserinfo',e)

		// 通过客户端方式能在增加记录时，createTime有默认值
		// const db = uniCloud.database()
		// const usersCollection = db.collection('user')
		// const a = await usersCollection.add({
		// 	openId:"openId",
		// 	nickName:"nickName",
		// 	avatarUrl:"avatarUrl",
		// 	lastLoginTime:"lastLoginTime"
		// })
		// console.log('addResult',a)
		// return

		// 获取code
		getCode((code) => {
			uni.showLoading({
				mask: true
			});

			uniCloud.callFunction({
				name: "wechat-login",
				data: {
					avatarUrl: e.detail.userInfo.avatarUrl,
					nickName: e.detail.userInfo.nickName,
					code: code
				}
			}).then(({
				result: res
			}) => {
				uni.hideLoading();
				// console.log('cf', res)
				if (res.errCode == 0) {
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					});

					try {
						uni.setStorageSync('userInfo', res.data);

						userInfo.value = res.data
						avatarUrl.value = res.data.avatarUrl
						nickName.value = res.data.nickName

						getSyncStorage()
					} catch (e) {
						console.log(e)
					}
				} else {
					uni.showToast({
						title: res.errMsg,
						icon: 'none'
					});
				}
			}).catch((e) => {
				uni.hideLoading();
				console.log(e)
			})
		})
	}

	// 获取code
	function getCode(callback) {
		wx.login({
			success(res) {
				if (res.code) {
					// console.log('获取code成功',res.code)
					callback(res.code)
				} else {
					console.log('获取code失败！' + res.errMsg)
				}
			},
			fail(errMsg) {
				console.log('获取code失败！', errMsg)
			}
		})
	}

	// 查看本地是否有数据
	function getSyncStorage() {
		try {
			const value = uni.getStorageSync("leaderboard");
			if (value) {
				uni.showModal({
					title: '本地有记录',
					content: '是否同步信息？',
					success: function(res) {
						if (res.confirm) {
							// console.log('用户点击确定');
							uni.showLoading({
								mask: true
							});
							uniCloud.callFunction({
								name: "update-batch-leaderboard",
								data: {
									userId: userInfo.value.userId,
									subject: value
								}
							}).then(({
								result: e
							}) => {
								uni.hideLoading();
								console.log('cf', e)
								if (e.errCode == 0) {
									uni.showToast({
										title: "同步成功",
										icon: 'none'
									});
								} else {
									uni.showToast({
										title: e.errMsg,
										icon: 'none'
									});
								}
							}).catch((e) => {
								uni.hideLoading();
								console.log(e)
							})
						}
					}
				});
			}
		} catch (e) {
			console.log(e)
		}
	}

	// 不是微信点击登录
	function toLogin() {
		uni.showToast({
			title: '敬请期待',
			icon: 'none'
		});
	}
	// 基于固定时间判断白天还是晚上
	function isDayOrNightSimple(dayStart = 6, dayEnd = 18) {
		const now = new Date();
		const hours = now.getHours();

		// 判断当前时间是否在白天时间段内
		if (hours >= dayStart && hours < dayEnd) {
			return 'day';
		} else {
			return 'night';
		}
	}
	
	// 排行榜
	function handleRank(){
		uni.navigateTo({
			url:"/pages/my/rank/rank"
		})
	}
	
	// 退出登录
	function handleQuit(){
		uni.showModal({
			title: '提示',
			content: '确定退出吗?',
			success: function (res) {
				if (res.confirm) {
					try {
						uni.removeStorageSync('userInfo');
						
						userInfo.value = null
						avatarUrl.value = ""
						nickName.value = ""
						avatarUrl.value = "/static/Rubik-s.png"
						
						uni.showToast({
							title: "已退出",
							icon: 'none'
						});
					} catch (e) {
						// error
					}
				} 
			}
		});
	}
</script>

<style>
	@import "my.css"
</style>